﻿using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Controls;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.SystemUI;
using Newtonsoft.Json;
using Swsk33.FinalCourseDesign.Control;
using Swsk33.FinalCourseDesign.DataObject;
using Swsk33.FinalCourseDesign.Frame;
using Swsk33.FinalCourseDesign.Model;
using Swsk33.FinalCourseDesign.src.Util;
using Swsk33.ReadAndWriteSharp.Network;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;

namespace Swsk33.FinalCourseDesign
{
	public partial class MainGUI : Form
	{
		/// <summary>
		/// 鼠标按下时在窗口中的x坐标
		/// </summary>
		private int mouseAtX;

		/// <summary>
		/// 鼠标按下时在窗口中的y坐标
		/// </summary>
		private int mouseAtY;

		/// <summary>
		/// 鼠标是否在窗口上是按下状态
		/// </summary>
		private bool isMouseDown = false;

		/// <summary>
		/// 当前位置
		/// </summary>
		public static IPoint CurrentPosition;

		public MainGUI()
		{
			CheckForIllegalCrossThreadCalls = false;
			InitializeComponent();
		}

		private void MainGUI_MouseDown(object sender, MouseEventArgs e)
		{
			Cursor = Cursors.SizeAll;
			mouseAtX = e.X;
			mouseAtY = e.Y;
			isMouseDown = true;
		}

		private void MainGUI_MouseMove(object sender, MouseEventArgs e)
		{
			if (isMouseDown)
			{
				Left = MousePosition.X - mouseAtX;
				Top = MousePosition.Y - mouseAtY;
			}
		}

		private void MainGUI_MouseUp(object sender, MouseEventArgs e)
		{
			Cursor = Cursors.Default;
			isMouseDown = false;
		}

		private void close_Click(object sender, EventArgs e)
		{
			Application.Exit();
		}

		/// <summary>
		/// 转至中心
		/// </summary>
		private void goCenter()
		{
			IPoint center = new PointClass();
			center.X = 118.708;
			center.Y = 32.205;
			mainMapControl.CenterAt(center);
		}

		private void MainGUI_Load(object sender, EventArgs e)
		{
			// 加载地图
			IRasterLayer layer = new RasterLayer();
			layer.CreateFromFilePath(Configure.GetConfigure().MapResource);
			mainMapControl.AddLayer(layer);
			// 禁止缩放
			mainMapControl.AutoMouseWheel = false;
			// 切换成手型工具
			ICommand cmd = new ControlsMapPanTool();
			cmd.OnCreate(mainMapControl.Object);
			mainMapControl.CurrentTool = (ITool)cmd;
			pan.BackColor = Color.SkyBlue;
			mainMapControl.MapScale = 5000;
			goCenter();
		}

		private void goToCenter_Click(object sender, EventArgs e)
		{
			goCenter();
		}

		private void locate_Click(object sender, EventArgs e)
		{
			ICommand setPosition = new SetPosition();
			setPosition.OnCreate(mainMapControl);
			mainMapControl.CurrentTool = (ITool)setPosition;
			locate.BackColor = Color.BlueViolet;
			pan.BackColor = Color.Transparent;
		}

		private void pan_Click(object sender, EventArgs e)
		{
			ICommand cmd = new ControlsMapPanTool();
			cmd.OnCreate(mainMapControl.Object);
			mainMapControl.CurrentTool = (ITool)cmd;
			pan.BackColor = Color.SkyBlue;
			locate.BackColor = Color.Transparent;
		}

		/// <summary>
		/// 获取当前位置到指定餐厅的距离
		/// </summary>
		/// <param name="canteen">指定餐厅</param>
		/// <returns>距离</returns>
		private double getCurrentToCanteenDistance(Canteen canteen)
		{
			return Math.Sqrt(Math.Pow(CurrentPosition.X - canteen.Longitude, 2) + Math.Pow(CurrentPosition.Y - canteen.Latitude, 2));
		}

		/// <summary>
		/// 做选择
		/// </summary>
		/// <param name="canteens">选择的餐厅列表</param>
		/// <param name="selectIndex">列表中被选中的餐厅索引</param>
		/// <param name="type">门店类型</param>
		private void doSelect(List<Canteen> canteens, int selectIndex, string type)
		{
			// 设定控件
			selectTip.Visible = true;
			go.Enabled = false;
			// 查找最近食堂并赋分
			if (CurrentPosition != null)
			{
				Canteen nearestCanteen = canteens[0];
				for (int i = 1; i < canteens.Count; i++)
				{
					if (getCurrentToCanteenDistance(canteens[i]) < getCurrentToCanteenDistance(nearestCanteen))
					{
						nearestCanteen = canteens[i];
					}
				}
				nearestCanteen.InitScore = nearestCanteen.InitScore + 17;
			}
			// 被选择的餐厅额外给分
			canteens[selectIndex].InitScore = canteens[selectIndex].InitScore + 19;
			// 执行排序，降序排列
			Canteen temp;
			for (int i = 0; i < canteens.Count - 1; i++)
			{
				for (int j = i; j < canteens.Count - i - 1; j++)
				{
					if (canteens[j].InitScore < canteens[j + 1].InitScore)
					{
						temp = canteens[j];
						canteens[j] = canteens[j + 1];
						canteens[j + 1] = temp;
					}
				}
			}
			// 取分值最大餐厅
			Canteen firstCanteen = canteens[0];
			// 根据餐厅和选择的类型获取候选门店
			string requestBody;
			try
			{
				requestBody = NetworkUtils.SendGetRequest(Configure.GetConfigure().Server + "/getstore/canteen/" + firstCanteen.Id + "/type/" + type);
			}
			catch (Exception)
			{
				MessageBox.Show("网络连接失败！请重试！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
				selectTip.Visible = false;
				go.Enabled = true;
				return;
			}
			Result<List<Store>> result = JsonConvert.DeserializeObject<Result<List<Store>>>(requestBody);
			if (result.Success)
			{
				selectTip.Visible = false;
				go.Enabled = true;
				// 从候选列表随机选择一个
				Random random = new Random();
				Store selectedStore = result.Data[random.Next(0, result.Data.Count)];
				// 标记在地图上
				IPoint canteenPoint = new PointClass();
				canteenPoint.X = firstCanteen.Longitude;
				canteenPoint.Y = firstCanteen.Latitude;
				mainMapControl.CenterAt(canteenPoint);
				DrawMarker.DrawSingleCanteenMarker(mainMapControl, firstCanteen, selectedStore);
			}
			else
			{
				MessageBox.Show("网络连接失败！请重试！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
				selectTip.Visible = false;
				go.Enabled = true;
				return;
			}
		}

		private void go_Click(object sender, EventArgs e)
		{
			SelectDialog dialog = new SelectDialog();
			if (dialog.ShowDialog() == DialogResult.OK)
			{
				doSelect(dialog.SelectCanteenList, dialog.SelectCanteenIndex, dialog.Type);
			}
		}
	}
}